package org.pliers.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.pliers.LbIsolationContextHolder;
import org.pliers.Mappers;
import org.pliers.exception.BusinessException;
import org.pliers.mapper.UserMapper;
import org.pliers.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RefreshScope
@RestController
public class ConfigClientController {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private UserMapper userMapper ;

    @GetMapping("/configInfo")
    public String  getConfigInfo() throws Exception {
        String version = LbIsolationContextHolder.getVersion() ;
        log.info("version:"+version );
        if("2.0".equals(version)){
            throw new BusinessException("出现了错误！") ;
        }

        List<User> users = userMapper.findAll() ;
        log.info("findAll result : {} ",Mappers.objectMapper.writeValueAsString(users));

        Set<String> names = new HashSet() ;
        names.add("Jone") ;
        names.add("Jack") ;
        users = userMapper.findUsersByName(names) ;
        log.info("findUsersByName result : {} ",Mappers.objectMapper.writeValueAsString(users));

        // 分页是从1开始的
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("id",2) ;
        Page<User> page = new Page<>(2, 3);
        IPage userPage = userMapper.page(page,queryWrapper) ;
        log.info("page result : {} ",Mappers.objectMapper.writeValueAsString(userPage));


        Page<User> page1 = new Page<>(1, 3);
        IPage userPage1 = userMapper.page(page1,queryWrapper) ;
        log.info("page result : {} ",Mappers.objectMapper.writeValueAsString(userPage1));

        User u1 = userMapper.selectById(1L) ;
        log.info("before update u1 result : {} ",Mappers.objectMapper.writeValueAsString(u1));
        u1.setName(u1.getName()+",new");
        int result = userMapper.updateById(u1) ;
        log.info("after update  result : {} ,u1 : {} ",result ,Mappers.objectMapper.writeValueAsString(u1));

        u1.setName("shenx");
        u1.setId(null);
        result = userMapper.insert(u1) ;
        log.info("after insert  result : {} ,u1 : {} ",result ,Mappers.objectMapper.writeValueAsString(u1));

        return ",这是serviece返回的信息，version："+ version ;
    }

}
